package com.declum.peyar.handler;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

/**
 * It stores the Responses to client from the server as Key/Value pair
 * 
 * @author clement
 * 
 */
public class ResponseHeader {
	/**
	 * Structure to stores the headers and values
	 */
	private HashMap<String, String> hashmap;

	/**
	 * Reason for Failure or Information of Success
	 */
	private String reason;

	/**
	 * Stores SUCCESS/FAILURE
	 */
	private String status;

	/**
	 * Initializes the internal structures
	 */
	public ResponseHeader() {
		this.hashmap = new HashMap<String, String>();
	}

	/**
	 * Return the value of a header specified
	 * 
	 * @param header
	 * @return
	 */
	public String getHeader(String header) {
		return this.hashmap.get(header);
	}

	/**
	 * It organizes the header/value as header:value and returns the String. For
	 * each header:value, '\r\n' will be the delimiters. End of the Headers will
	 * be marked as '\r\n\r\n'.
	 * 
	 * @return
	 */
	public String getHeaders() {
		String value = "";
		Entry<String, String> entry;
		value += "Status: " + this.status + "\r\n";
		if (this.reason != null) {
			value += "Reason: " + this.reason + "\r\n";
		}
		Iterator<Entry<String, String>> iterator = this.hashmap.entrySet()
				.iterator();
		while (iterator.hasNext()) {
			entry = iterator.next();
			value += entry.getKey() + ": " + entry.getValue() + "\r\n";
		}
		return value + "\r\n";
	}

	/**
	 * Returns the Reason of response
	 * 
	 * @return
	 */
	public String getReason() {
		return this.reason;
	}

	/**
	 * Returns the Status of the Response
	 * 
	 * @return
	 */
	public String getStatus() {
		return this.status;
	}

	/**
	 * Set a value to a header
	 * 
	 * @param header
	 * @param value
	 */
	public void setHeader(String header, String value) {
		this.hashmap.put(header, value);
	}

	/**
	 * Set the Reason of response
	 * 
	 * @param reason
	 */
	public void setReason(String reason) {
		this.reason = reason;
	}

	/**
	 * Set the status of the response
	 * 
	 * @param status
	 */
	public void setStatus(String status) {
		this.status = status;
	}

	@Override
	public String toString() {
		return this.getHeaders();
	}
}
